package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.domain.*;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.service.MemberService;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashSet;
import java.util.List;

@RestController
@RequestMapping("/member")
public class MemberController {
    @Reference
    MemberService memberService;

    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {
        PageResult pageResult = memberService.findPage(queryPageBean);
        return pageResult;
    }

    @RequestMapping("/add")
    public Result add( String username,@RequestBody Member member) {

        try {
            member.setUsername(username);
            memberService.add(member);
            return new Result(true, MessageConstant.ADD_MEMBER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ADD_MEMBER_FAIL);
        }

    }

    @RequestMapping("/findById")
    public Result add(Integer id) {
        try {
            Member member = memberService.findSingleMember(id);
            return new Result(true, MessageConstant.EDIT_MEMBER_SUCCESS, member);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.EDIT_MEMBER_FAIL);
        }

    }
    @RequestMapping("/edit")
    public Result edit(String username, @RequestBody Member member) {
        System.out.println(username +"--"+member);
        try {
            member.setUsername(username);
            memberService.update(member);
            System.out.println(member);
            return new Result(true, MessageConstant.EDIT_MEMBER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.EDIT_MEMBER_FAIL);
        }
    }
    @RequestMapping("/delete")
    public Result delete(Integer id) {
        try {
            memberService.delete(id);
            return new Result(true, MessageConstant.DELETE_MEMBER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "该数据有外键关联,请解除关联关系后重试");
        }
    }
    @RequestMapping("/exportExcel")
    public Result exportExcel(String ids, HttpServletRequest request, HttpServletResponse response) {
        System.out.println(ids);
        String[] id = ids.split(",");
        String filePath = request.getSession().getServletContext().getRealPath("template") + File.separator + "total.xlsx";
        try {
            Workbook excel = new XSSFWorkbook(new FileInputStream(new File(filePath)));
            //读取第一个表
            Sheet sheetAt = excel.getSheetAt(0);

            int lastRowNum = sheetAt.getLastRowNum();

            System.out.println("lastRowNum = " + lastRowNum);
            if (id !=null &&id.length !=0) {
                for (int i = 0; i < id.length; i++) {

                    int s = Integer.parseInt(id[i]);
                    Member member = memberService.findById(s);

                    //创建第二行
                    Row row = sheetAt.createRow(i + 1);
                    //创建列
                    row.createCell(0).setCellValue(member.getName());
                    row.createCell(1).setCellValue(member.getSex());
                    row.createCell(2).setCellValue(member.getPhoneNumber());
                    List<Order> orderList = member.getOrderList();

                    if (orderList != null) {
                        Cell cell1 = row.createCell(3);//机构地址
                        Cell cell2 = row.createCell(4);//套餐名称
                        Cell cell3 = row.createCell(5);//检查组名称
                        Cell cell4 = row.createCell(6);//检查项
                        HashSet<String> hashSet4 = new HashSet<>();//存放地址
                        HashSet<String> hashSet1 = new HashSet();//存放套餐
                        HashSet<String> hashSet2 = new HashSet();//存放检查组
                        HashSet<String> hashSet3 = new HashSet();//存放检查项
                        for (Order order : orderList) {
                            Setmeal setmeal = order.getSetmeal();
                       List<Address> addressList = order.getAddressList();
                            System.out.println(addressList);
                            if (addressList !=null){
                                for (Address address : addressList) {
                                    String name = address.getName();
                                    hashSet4.add(name);
                                }
                            }
                            hashSet1.add(setmeal.getName() + " ");
                            List<CheckGroup> checkGroups = setmeal.getCheckGroups();
                            if (checkGroups != null) {
                                for (CheckGroup checkGroup : checkGroups) {
                                    hashSet2.add(checkGroup.getName() + " ");
                                    List<CheckItem> checkItems = checkGroup.getCheckItems();
                                    if (checkItems != null) {
                                        for (CheckItem checkItem : checkItems) {
                                            String name = checkItem.getName();
                                            hashSet3.add(name + " ");
                                        }
                                    }
                                }
                            }
                            StringBuilder str1 = new StringBuilder();
                            StringBuilder str2 = new StringBuilder();//存放检查组信息
                            StringBuilder str3 = new StringBuilder();
                            StringBuilder str4 = new StringBuilder();
                            for (String s1 : hashSet1) {
                                str1.append(s1);
                            }
                            for (String s2 : hashSet2) {
                                str2.append(s2);
                            }
                            for (String s3 : hashSet3) {
                                str3.append(s3);
                            }
                            for (String s4: hashSet4) {
                                str4.append(s4);
                            }
                            //设置样式
                            CellStyle cellStyle = excel.createCellStyle();
                            cellStyle.setWrapText(true);
                            cell1.setCellStyle(cellStyle);
                            cell2.setCellStyle(cellStyle);
                            cell3.setCellStyle(cellStyle);
                            cell4.setCellStyle(cellStyle);
                            //添加数据
                            cell2.setCellValue(str1.toString());
                            cell3.setCellValue(str2.toString());
                            cell4.setCellValue(str3.toString());
                            cell1.setCellValue(str4.toString());
                        }
                    }

                }
            }
            OutputStream out = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");//代表的是Excel文件类型
            response.setHeader("content-Disposition", "attachment;filename=total.xlsx");//指定以附件形式进行下载
            excel.write(out);
            out.flush();
            out.close();
            excel.close();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }
}
